
"""

mysql 数据库连接池

"""


import pymysql
import yaml
from dbutils.pooled_db import PooledDB

with open('config/db_formal.yaml','r', encoding='utf-8') as f:
    data = f.read()
    yaml_reader = yaml.load(data, Loader=yaml.CLoader)

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数，0和None表示不限制连接数
    mincached=2,  # 初始化时，链接池中至少创建的链接，0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
    ping=0, # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always

    host=yaml_reader["mysql"]["host"],
    port=yaml_reader["mysql"]["port"],
    user=yaml_reader["mysql"]["user"],
    password=yaml_reader["mysql"]["password"],
    database=yaml_reader["mysql"]["database"]

    # host = "192.168.31.138",
    # port = 3306,
    # user = "root",
    # password = "root",
    # database = "elevator_03"
)

def get_conn():


    conn = POOL.connection()
    cursor = conn.cursor()

    return conn,cursor
def close_conn(conn,cursor):
    cursor.close()
    conn.close()
    return '1'

def fetchall(sql,*args):
    """ 获取所有数据 """
    try:
        conn,cursor = get_conn()
        cursor.execute(sql,args)
        result = cursor.fetchall()

        close_conn(conn,cursor)
    except Exception as e:
        bb.error(e)
    return result

def fetchone(sql, *args):
    """ 获取单挑数据 """
    conn, cursor = get_conn()
    cursor.execute(sql, args)
    result = cursor.fetchone()
    close_conn(conn, cursor)
    return result

def insert_data(sql,*args):
    conn,cursor = get_conn()
    cursor.execute(sql, *args)
    conn.commit()
    close_conn(conn, cursor)
    return '1'

def delete_data(sql,*args):
    conn,cursor = get_conn()
    cursor.execute(sql, *args)
    conn.commit()
    close_conn(conn, cursor)
    return '1'

def edit_data(sql,*args):
    try:
        conn,cursor = get_conn()
        cursor.execute(sql, *args)
        conn.commit()
        close_conn(conn, cursor)
        return '1'
    except Exception as e:
        bb.error(e)


if __name__ == '__main__':
    # sql = "update cs2 set Confidence='0,0.75,0,0.80,0.6,0.5' where id = 1"
    # edit_data(sql)
    # # sql = "select * from cs"



    sql_1="select * from ep_equipdata limit 2"
    re = fetchall(sql_1)
    print(re)

